package com.matete.agentmanage.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.matete.agentmanage.common.utils.CommonUtils;
import com.matete.agentmanage.common.utils.JavaTranslate;
import com.matete.agentmanage.common.utils.UploadUtils;
import com.matete.agentmanage.model.Room;
import com.matete.agentmanage.model.User;
import com.matete.agentmanage.service.RechargeService;
import com.matete.agentmanage.service.RoomService;
import com.matete.agentmanage.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 框架控制器
 * 
 * @author lxf
 */
@Clear
public class DataController extends Controller {
	public static final RechargeService rechargeService = new RechargeService();
	public static final RoomService roomService = new RoomService();
	public static final UserService userService = new UserService();
	
	/**
	 * 外界获取room基本信息的接口
	 */
	public void index() {
		List<Room> rooms = rechargeService.getRoomsInformation();
		renderJson(rooms);
	}
	
	/**
	 * 将微信端所发送的请求直接存储在数据库中
	 */
	public void addRequest() {
		JavaTranslate javaTranslate = new JavaTranslate();
		//Room room = roomService.getRoom(getPara("ID"));
		User user = new User();
		String ID = getPara("ID");
		String Name = getPara("name");
		String Phone = getPara("phone");
		String Date = getPara("date");
		String StartTime = getPara("startTime");
		String EndTime = getPara("endTime");
		String Info = getPara("info");
		user.setRoomID(Integer.valueOf(ID));
		user.setInfo(Info);
		user.setDate(javaTranslate.StringToSQLDate(Date));
		user.setEndTime(javaTranslate.StringToDatetime(Date + " " + EndTime + ":00"));
		user.setPhone(Phone);
		user.setUserName(Name);
		user.setStartTime(javaTranslate.StringToDatetime(Date + " " + StartTime + ":00"));
		user.save();
		System.out.println(Name + Phone + getPara("ID"));
		
		// 查询代理级别下拉
		//List<Record> agentLevelList = roomService.getPropertyList(GlobalSettings.PROPERTY_KEY_AGENTLEVEL);
		//setAttr("agentLevelList", agentLevelList);
		//renderJsp("req_room.jsp");

	}

	/**
	 * 会议室归还接口
	 */
	public void returnRoom(){
		// 数据的接收
		// 文件上传的基作
		try {
			// 定义一个Map集合用于保存接收到的数据
			Map<String, String> map = new HashMap<String, String >();
			// 1. 创建一个磁盘文件项工厂对象
			DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
			// 2. 创建一个核心解析类
			ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
			// 3. 解析request请求ist集合中存放的是FileItem对象
			List<FileItem> list = servletFileUpload.parseRequest(getRequest());
			// 4. 遍历集合，获得每个FileItem，判断是表单项还是文件上传项
			String url = null;
			for (FileItem fileItem : list) {
				// 判断是表单项还是文件上传项
				if (fileItem.isFormField()) {
					// 普通表单项
					// 接受表单项参数的值
					String name = fileItem.getFieldName();
					String value = fileItem.getString("UTF-8");
					// 如果存在任意空值 则返回false
					if (value == "" || "".equals(value)) {
						renderJson(false);
						return;
					}
					System.out.println(name + " " + value);
					map.put(name, value);  // 将数据存储，第二次会覆盖
				} else {
					// 文件上传项
					// 文件上传功能
					// 获得文件上传的名称
					String fileName = fileItem.getName();
					if (fileName != null && !"".equals(fileName)) {
						// 通过工具类获得唯一文件名
						String uuidFileName = UploadUtils.getUUIDFileName(fileName);
						// 获得文件上传的数据
						InputStream is = fileItem.getInputStream();
						// 获得文件上传的路径
						String path = this.getRequest().getServletContext().getRealPath("/upload");
						System.out.println(path);
						// 将输入流对接到输出流
						url = path + "\\" + uuidFileName;
						OutputStream os = new FileOutputStream(url);
						int len = 0;
						byte[] b = new byte[1024];
						while ((len = is.read(b)) != -1) {
							os.write(b);
						}
						is.close();
						os.close();
					}
                    map.put("url" , url);
				}
			}
            // 判断手机号与解锁码是否配对
            if (!userService.selectUser(map.get("phone"), map.get("lock"))) {
                // 如果没有成功匹配
                renderJson(false);
                return;
            } else {
			    // 如果成功匹配,将map对象存储到数据库中
                roomService.saveReturnRoom(map,userService.useUser(map.get("phone"), map.get("lock")));
                renderJson(true);
            }
            System.out.println(map);
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(false);
		}
	}
	
}